package com.yequan.datastructure.algorithm;

/**
 * 轮询算法简单实现
 * 用于分区
 * 用数字进行分区,从1开始
 *
 * @author yequan
 * @date 2019/12/09
 */
public class Partition {

    /**
     * 分区总数
     */
    private int size;
    /**
     * 分区大小
     */
    private int partitionSize;
    /**
     * 区间个数
     */
    private int partitionCount;

    public Partition(int size, int partitionSize) {
        if (size <= 0 || partitionSize <= 0) {
            throw new IllegalArgumentException("参数错误");
        }
        this.size = size;
        this.partitionSize = partitionSize;
        initPartitionCount();
    }

    /**
     * 初始化区间个数
     */
    private void initPartitionCount() {
        //确认分几个区间
        partitionCount = size / partitionSize;
        int mod = size % partitionSize;
        if (mod > 0) {
            partitionCount++;
        }
    }

    /**
     * 获取所有的区间个数
     *
     * @return
     */
    public int[] getAllPartition() {
        int[] partitions = new int[partitionCount];
        for (int i = 0; i < partitionCount; i++) {
            partitions[i] = i + 1;
        }
        return partitions;
    }

    /**
     * 根据传入的id获取区间位置
     * 区间位置从1开始
     *
     * @param num
     * @return
     */
    public int getPartition(int num) {
        if (num < 0) {
            throw new IllegalArgumentException("参数错误");
        }
        return (num % partitionCount) + 1;
    }

    public static void main(String[] args) {
        Partition partition = new Partition(1999, 100);
        int[] allPartition = partition.getAllPartition();
        for (int i = 0; i < allPartition.length; i++) {
            System.out.println("区间号: " + allPartition[i]);
        }
        int partitionNum = partition.getPartition(1999);
        System.out.println(1999 + " 分区为:  " + partitionNum);
    }

}
